package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

var FILE_PATH = flag.String("f", "./", "the  file path")
var FILE_EXT = flag.String("e", "pdf", "the file extension")

func main() {
	// 指定要搜索的目录
	flag.Parse()
	dir := *FILE_PATH
	fmt.Println("dir:", dir)
	//dir := "E:/work/资料/充电桩标准"
	// 1. 查询目录下的PDF文件
	pdfFiles, err := findPDFFiles(dir, *FILE_EXT)
	if err != nil {
		fmt.Printf("查找PDF文件出错: %v\n", err)
		return
	}

	if len(pdfFiles) == 0 {
		fmt.Println("没有找到PDF文件")
		return
	}

	fmt.Printf("找到 %d 个PDF文件:\n", len(pdfFiles))
	for _, file := range pdfFiles {
		fmt.Println(file)
		base := filepath.Base(file)
		err := copyWithBuffer(file, base+".bin")
		fmt.Println(err)

	}
}

// 查找目录下的PDF文件
func findPDFFiles(dir, ext string) ([]string, error) {
	var pdfFiles []string

	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return nil, err
	}

	for _, file := range files {
		if !file.IsDir() && strings.HasSuffix(strings.ToLower(file.Name()), "."+ext) {
			pdfFiles = append(pdfFiles, filepath.Join(dir, file.Name()))
		}
	}

	return pdfFiles, nil
}

func copyWithBuffer(src, dst string) error {
	source, err := os.Open(src)
	if err != nil {
		return err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer destination.Close()

	// 使用缓冲区
	buf := make([]byte, 1024*1024) // 1MB缓冲区
	reader := bufio.NewReader(source)
	writer := bufio.NewWriter(destination)

	for {
		n, err := reader.Read(buf)
		if err != nil && err != io.EOF {
			return err
		}
		if n == 0 {
			break
		}

		if _, err := writer.Write(buf[:n]); err != nil {
			return err
		}
	}

	return writer.Flush()
}
